#!/usr/bin/env python
# coding: utf-8

# Setp one:
# note: Reload django settings
import datetime
import logging
import os
import sys
import time
import xlrd
import django
from dateutil.relativedelta import relativedelta

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
os.chdir(os.path.join(BASE_DIR, "yijiao_main"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
sys.path.insert(0, os.path.join(BASE_DIR, "pylib"))
sys.path.insert(0, os.path.join(BASE_DIR, "yijiao_main"))
django.setup()

# Setp two:
# note: Load function with logging, django model
from services.datamodel.student.models import mm_Student
from services.datamodel.product.models import mm_ProductUse

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    filename=os.path.join("/tmp", "open_member_offline.log")
)


# Setp three:
# note: Running
def update_member(user_id, product_id, month):
    now = datetime.datetime.now()
    p = mm_ProductUse.get_or_create(user_id=user_id, product_id=product_id, defaults={
        "status": 1,
        "purchasetype": 1,
        "create_time": now,
        "effectiveenddate": now + relativedelta(months=month),
    })
    if not p[1]:
        p[0].status = 1
        p[0].purchasetype = 1
        p[0].effectiveenddate = max(now, p[0].effectiveenddate) + relativedelta(months=month)
        p[0].save()
        logging.info("更新了user_id: {}, product_ud: {}, 有效期 {}个月。".format(user_id, product_id, month))
    else:
        logging.info("新建了user_id: {}, product_ud: {}, 有效期 {}个月。".format(user_id, product_id, month))


def open_member_offline():
    count_info = {}
    f = os.path.join(BASE_DIR, "yijiao_main", "services\script_offline\member.xlsx")
    sheet = xlrd.open_workbook(f)
    table = sheet.sheet_by_name("sheet")
    # 姓名    帐号    数学   科学  月份
    # 李家宏  ljh02   0     1     7
    for one_line in table.get_rows():
        count = one_line[1].value
        name = one_line[0].value
        math = True if one_line[2].value else False
        science = True if one_line[3].value else False
        month = one_line[4].value
        count_info[count] = {
            "name": name,
            "math": math,
            "science": science,
            "month": month,
        }
    count_info.pop("帐号", None)
    count_info.pop("", None)

    student_instances = mm_Student.filter(user__username__in=list(count_info.keys()))
    for info in student_instances.values("realname", "user_id", "user__username"):
        count_info.get(info["user__username"], {}).update(info)

    for count, info in count_info.items():
        yes_or_no = True
        if not info.get("realname"):
            logging.error("帐号错误：姓名是{}，帐号是{}".format(info["name"], count))
            continue
        elif info.get("name") != info.get("realname"):
            print("学生名字不一致，后台是{}，表格是{}，是否更新会员信息： ".format(info.get("realname"), info.get("name")))
            while True:
                yes_or_no = input("if update(yes or no): ").strip().lower()
                if yes_or_no in ["no", "n"]:
                    yes_or_no = False
                    break
                elif yes_or_no in ["yes", "y"]:
                    yes_or_no = True
                    break
        if not yes_or_no:
            logging.error("没有更新会员{}的信息： 学生名字不一致，后台是{}，表格是{}".format(count, info.get("realname"), info.get("name")))
            continue
        if info["math"]:
            update_member(info["user_id"], 1, int(info["month"]))
        if info["science"]:
            update_member(info["user_id"], 2, int(info["month"]))


if __name__ == "__main__":
    start_time = time.time()
    open_member_offline()
    logging.info("end")
    print(time.time() - start_time)
